package com.xdh.springcloud.security.jwt;

import com.xdh.springcloud.common.message.Message;
import com.xdh.springcloud.common.message.MessageCode;
import com.xdh.springcloud.security.jwt.common.config.AuthConfig;
import com.xdh.springcloud.security.jwt.common.factory.JwtTokenFactory;
import com.xdh.springcloud.security.jwt.common.model.JwtToken;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
public class TokenController {

    @Autowired
    private JwtTokenFactory jwtTokenFactory;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = AuthConfig.VERIFY_TOKEN_URL,produces = {MediaType.APPLICATION_JSON_VALUE})
    public Message verifyToken(HttpServletRequest request) {
        String tokenPayload = request.getHeader(AuthConfig.AUTHENTICATION_HEADER_NAME);
        Message message = new Message();
        message.setCode(MessageCode.SUCCESS.getCode());
        try {
            jwtTokenFactory.parseClaims(tokenPayload);
        } catch (Exception e) {
            message.setCode(MessageCode.FAIL.getCode());
            message.setMsg(e.getMessage());
            logger.error("", e);
        }
        return message;
    }

    @RequestMapping(value = AuthConfig.REFRESH_TOKEN_URL,produces = {MediaType.APPLICATION_JSON_VALUE})
    public Message refreshToken(HttpServletRequest request) {
        String tokenPayload = request.getHeader(AuthConfig.AUTHENTICATION_HEADER_NAME);
        Message message = new Message();
        message.setCode(MessageCode.SUCCESS.getCode());
        try {
            Jws<Claims> claimsJws = jwtTokenFactory.parseClaims(tokenPayload);
            JwtToken jwtToken = jwtTokenFactory.refreshJwtToken(claimsJws);
            jwtTokenFactory.createMessage(jwtToken,message);
        } catch (Exception e) {
            message.setCode(MessageCode.FAIL.getCode());
            message.setMsg(e.getMessage());
            logger.error("", e);
        }
        return message;
    }
}
